<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>select_version</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"
        crossorigin="anonymous"></script>
</head>

<body>
    <ul class="nav nav-tabs">
        <li class="nav-item">
            <a class="nav-link active" data-toggle="tab" href="#server-version-table"
                data-url="http://127.0.0.1:6021/api/version/versions/?type=server" id="server-tab">服务端</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" data-toggle="tab" href="#client-version-table"
                data-url="http://127.0.0.1:6021/api/version/versions/?type=client" id="client-tab">客户端</a>
        </li>
    </ul>
    <ul class="nav justify-content-end">
        <li class="nav-item">
            <button type="button" class="btn btn-primary" data-bs-toggle="modal" id="add-version-btn"
                data-bs-target="#addingModal">新增</button>
            <!-- Modal -->
            <div class="modal fade" id="addingModal" tabindex="-1" aria-labelledby="exampleModalLabel"
                aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h1 class="modal-title fs-5" id="exampleModalLabel">增加新项</h1>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <form id="add-version-form">
                                <div class="mb-3">
                                    <label for="version-input" class="form-label"><strong>版本号</strong></label>
                                    <input type="text" class="form-control" id="version-input" required>
                                    <div id="version-error" class="text-danger vis-hidden">
                                        请重试：<strong>版本号格式</strong>应形如：<strong>v1.0.0</strong></div>
                                </div>
                                <div class="mb-3">
                                    <label for="description-input" class="form-label"><strong>描述</strong></label>
                                    <textarea class="form-control" id="description-input"></textarea>
                                </div>
                                <div class="mb-3">
                                    <label for="type-input" class="form-label"><strong>类型</strong></label>
                                    <select class="form-select" id="type-input">
                                        <option value="server">server</option>
                                        <option value="client">client</option>
                                    </select>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" onclick="addNewItem()">Add new one!</button>
                        </div>
                    </div>
                </div>
            </div>
            <!-- End of Modal -->
            <!-- Invisible Alert -->
            <div id="alert" class="alert alert-danger position-fixed top-0 start-50 translate-middle-x d-none"
                role="alert">
                新增请求失败，请更改<strong>ID格式</strong>形如<strong>v1.0.0</strong>然后重试
            </div>
            <!-- Alert -->
        </li>
    </ul>
    <div class="table-responsive">
        <div class="tab-content">
            <div class="tab-pane fade show active" id="server-version-table">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>版本号</th>
                            <th>类型</th>
                            <th>描述</th>
                            <th>是否最新</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="server-version-table-body"></tbody>
                </table>
            </div>
            <div class="tab-pane fade" id="client-version-table">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>版本号</th>
                            <th>类型</th>
                            <th>描述</th>
                            <th>是否最新</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="client-version-table-body"></tbody>
                </table>
            </div>
        </div>
    </div>

    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script>

        let alertTimeoutId = null;//弹窗警告1.4s内只会触发一次
        let baseUrl = 'http://127.0.0.1:6021/api/version/versions/';
        let currentTab = '#server-version-table';//默认值为#server-version-table,也可为client-version-table

        function init_select() {
            // 默认请求server数据
            const serverVersionTableBody = document.getElementById('server-version-table-body');
            const clientVersionTableBody = document.getElementById('client-version-table-body');

            fetchAndPopulateTable(baseUrl, serverVersionTableBody);

            // Tab的点击事件
            $('.nav-link').on('click', function (e) {
                e.preventDefault();
                // 取消所有Tab的选中状态
                $('.nav-link').removeClass('active');
                // 选中当前被点击的Tab
                $(this).addClass('active');
                // 获取当前被点击的Tab对应的tab-pane的id
                const tabContentId = $(e.target).attr('href');
                currentTab = tabContentId;
                // 获取当前被点击的Tab对应的tab-pane元素
                const tabContent = $(tabContentId);
                //取消所有tab-pane的显示状态
                $('.tab-pane').removeClass('active');
                $('.tab-pane').removeClass('show');
                // 手动设置tab-pane的属性
                tabContent.addClass('active');
                tabContent.addClass('show');
                // 获取表格的tbody元素
                const tableBody = tabContent.find('tbody')[0];
                const url = $(e.target).data('url');
                fetchAndPopulateTable(url, tableBody);
            });
            $('#version-input').on('focus input', function () {
                $('#version-error').addClass('vis-hidden');
                $('#version-input').removeClass('error');
            });
        }

        function fetchAndPopulateTable(url, tableBody) {
            $.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: data => {
                    // 将数据添加到表格中
                    tableBody.innerHTML = '';
                    data.data.results.forEach(result => {
                        const row = document.createElement('tr');

                        const versionCell = document.createElement('td');
                        versionCell.textContent = result.version;
                        row.appendChild(versionCell);

                        const typeCell = document.createElement('td');
                        typeCell.textContent = result.type;
                        row.appendChild(typeCell);

                        const descriptionCell = document.createElement('td');
                        descriptionCell.textContent = result.description;
                        row.appendChild(descriptionCell);

                        const isLatestCell = document.createElement('td');
                        isLatestCell.textContent = result.is_latest ? '是' : '否';
                        row.appendChild(isLatestCell);

                        const operationCell = document.createElement('td');

                        const deprecateButton = document.createElement('button');
                        deprecateButton.classList.add('btn', 'btn-sm', 'btn-secondary', 'mx-1');
                        deprecateButton.textContent = '弃用';
                        deprecateButton.addEventListener('click', function () {
                            deleteItem(result.id);
                            // 重新获取数据并刷新表格
                            fetchAndPopulateTable(url, tableBody);
                        });
                        operationCell.appendChild(deprecateButton);

                        const setLatestButton = document.createElement('button');
                        setLatestButton.classList.add('btn', 'btn-sm', 'btn-success', 'mx-1');
                        setLatestButton.textContent = '设为最新';
                        setLatestButton.addEventListener('click', function () {
                            setLatestItem(result.id);
                            // 重新获取数据并刷新表格
                            fetchAndPopulateTable(url, tableBody);
                        });
                        operationCell.appendChild(setLatestButton);

                        row.appendChild(operationCell);
                        tableBody.appendChild(row);
                    });
                },
                error: (xhr, status, error) => {
                    console.error('请求数据失败：', error);
                }
            });
        }

        //Version format validator,used in modal.
        function validateVersion(version) {
            // Remove any whitespace
            version = version.replace(/\s/g, '');

            // Convert the first letter to lowercase
            version = version.charAt(0).toLowerCase() + version.slice(1);

            // Check if the version matches the desired pattern
            var pattern = /^v?\d+(\.\d+)*$/;
            if (!pattern.test(version)) {
                // Display error message and highlight input field
                $('#version-error').removeClass('vis-hidden');
                $('#version-input').addClass('error');
                return false;
            }

            // Hide error message and restore input field
            $('#version-error').addClass('d-none');
            $('#version-input').removeClass('error');

            return true;
        }

        //Corresponding to the modal
        function addNewItem() {
            // Retrieve form inputs
            let version = $('#version-input').val();
            let description = $('#description-input').val();
            let type = $('#type-input').val();
            console.log(version, description, type);
            // Validate required fields
            if (!validateVersion(version)) {
                return false;
            }

            // Create JSON object
            let data = {
                version: version,
                description: description,
                type: type
            };
            console.log(data);
            // Send POST request to the API endpoint
            $.ajax({
                url: baseUrl,
                type: 'POST',
                dataType: 'json',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (response) {
                    console.log(`成功！返回信息为:`, response);
                    location.reload();
                    fetchAndPopulateTable(url, tableBody)
                },
                error: function (xhr, status, error) {
                    console.log(xhr.responseJSON.message);
                }
            });

            // Close the modal
            $('#addingModal').modal('hide');
        }

        //Set an item to lateset
        function setLatestItem(id) {
            const targetUrl = baseUrl + id + '/';
            console.log(targetUrl);
            $.ajax({
                type: "PATCH",
                url: targetUrl,
                dataType: "json",
                success: res => {
                    console.log(res);
                    location.reload();
                    if (currentTab === '#server-version-table') {
  $('#server-tab').tab('show');
} else {
  $('#client-tab').tab('show');
}
                },
                error: function (xhr, status, error) {
                    console.error('请求数据失败：', error);
                }
            });
        }

        function deleteItem(id) {
            const targetUrl = baseUrl + id + "/";
            $.ajax({
                type: "DELETE",
                url: targetUrl,
                dataType: "json",
                success: res => {
                    console.log(res);
                    location.reload();
                },
                error: function (xhr, status, error) {
                    console.error('请求数据失败：', error);
                }
            });
        }

        $(function () {
            init_select();
        })
    </script>
</body>
<style>
    /* Add a red border to the version input when there is an error */
    #version-input.error {
        border-color: red;
    }

    .vis-hidden {
        visibility: hidden;
    }

    table {
        width: 100%;
        border-collapse: collapse;
        table-layout: fixed;
    }

    td {
        padding: 10px;
        text-align: center;
        border: 1px solid black;
    }

    td button {
        flex-grow: 1;
        margin: 0 5px;
    }

    thead tr {
        text-align: center;
    }

    ::-webkit-scrollbar {
        width: 5px;
        height: 5px;
        background-color: #F5F5F5;
    }

    ::-webkit-scrollbar-thumb {
        -webkit-box-shadow: inset 0 0 2.5px rgba(0, 0, 0, .3);
        box-shadow: inset 0 0 2.5px rgba(0, 0, 0, .3);
        border-radius: 2.5px;
        background-color: #294E80;
        opacity: .7;
        transition: opacity ease-in-out 200ms;
    }

    ::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 2.5px rgba(0, 0, 0, 0.3);
        box-shadow: inset 0 0 2.5px rgba(0, 0, 0, 0.3);
        border-radius: 2.5px;
        background-color: #F5F5F5;
    }

    #alert {
        top: 20px;

        z-index: 10000;
    }
</style>

</html>